<template>
  <div id="map" style="width: 100%; height: 400px;"></div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';

import _axios from '@/api/request';

const emit = defineEmits(['update:longitude', 'update:latitude', 'update:inputValAddress'])
var map
var marker
var center
const { longitude, latitude, inputValAddress } = defineProps({
  longitude: {
    type: Number,
    default: 39.916527
  },
  latitude: {
    type: Number,
    default: 116.397128
  },
  inputValAddress: {
    type: String,
    default: ''
  },
})
function init() {
  const mapId = document.getElementById('map')
  if (longitude) {
    center = new qq.maps.LatLng(longitude, latitude)
  } else {
    center = new qq.maps.LatLng(39.916527, 116.397128)
  }
  map = new qq.maps.Map(mapId, {
    center: center, // 设定中心点坐标
    zoom: 13 // 设定地图显示的缩放级别
  });
  marker = new qq.maps.Marker({
    position: center,
    map: map
  });
  function getAddressByCoordinate(lat, lng) {//查询详细地址信息
    var geocoder = new qq.maps.Geocoder({
      complete: function (result) {
        if (result.detail.address !== '') {
          emit('update:inputValAddress', result.detail.address)
        }
      }
    });
    var coord = new qq.maps.LatLng(lat, lng); // 设置坐标点
    geocoder.getAddress(coord); // 根据坐标点查询详细地址信息
  }
  qq.maps.event.addDomListener(map, "click", function (event) {
    if (!marker) {
      marker = new qq.maps.Marker({
        position: event.latLng,
        map: map
      });
    }
    emit('update:longitude', event.latLng.lng)
    emit('update:latitude', event.latLng.lat)
    marker.setPosition(event.latLng);
    getAddressByCoordinate(event.latLng.lat, event.latLng.lng)
  })
}
var searchService = new qq.maps.SearchService({
  complete: function (results) {
    console.log(results);
    if (results.type === "CITY_LIST") {
      searchService.setLocation(results.detail.cities[0].cityName);
    }
    marker.setMap(null)
    var pois = results.detail.pois;
    if (pois?.length) {
      var latlngBounds = new qq.maps.LatLngBounds();
      var poi = pois[0];
      latlngBounds.extend(poi.latLng);
      emit('update:longitude', poi.latLng.lng)
      emit('update:latitude', poi.latLng.lat)
      emit('update:inputValAddress', poi.name)
      center = new qq.maps.LatLng(poi.latLng.lng, poi.latLng.lat)
      marker = new qq.maps.Marker({
        map: map,
        position: center
      });
      marker.setPosition(poi.latLng);
      map.fitBounds(latlngBounds);
    }
  }
});
function search(val) {
  //调用Poi检索类。用于进行本地检索、周边检索等服务。
  searchService.search(val)
}
onMounted(() => {
  init()
})
defineExpose({
  search
})
</script>